#!/usr/bin/env python
import commands
import sys
from string import strip
from string import split
import datetime
import logging
from conf import hostconf



logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',level=logging.INFO)


_getpidcmd = 'ssh weixin@%s -C "cat /tmp/tomcat_8080.pid"'

_killpidcmd = 'ssh weixin@%s -C "kill -9 %s"'

_bakcmd = 'ssh weixin@%s -C "cp -r %s %s"'

_mkpath = 'ssh weixin@%s -C "mkdir %s"'

_uploadcmd = 'scp -r %s weixin@%s:%s'

_startcmd = 'ssh weixin@%s -C "/data/server/tomcat_8080/bin/startup.sh"'


def execmd(cmd):
    logging.info('[CMD]:%s' % cmd)
    status,output = commands.getstatusoutput(cmd)
    return output


def dpwithrestart(conf):
    """
    upgrade some file with restart tomcat
    """

    host = conf['host']
    logging.info('begining to deploy : %s' % conf['desc'])
    #kill process
    pid = execmd(_getpidcmd % host)


    logging.info('host : %s pid is %s will be killed.' % (host,pid))

    
    execmd(_killpidcmd % (host,pid))



    ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')

    srcpath = conf['remote']
    dstpath = srcpath + '_' + ts

    logging.info('backup files from %s to %s .' % (srcpath,dstpath))
    execmd(_bakcmd % (host,srcpath,dstpath))


    #print 'mkdir %s at %s' % (srcpath,host)

    #execmd(_mkpath % (host,srcpath))

    localpath = conf['local']
    logging.info('upgrade : ' + _uploadcmd % (localpath,host,conf['remote']))

    execmd(_uploadcmd % (localpath,host,conf['remote']))

    logging.info('startup tomcat.')

    execmd(_startcmd % host)

    logging.info('%s deploy over.' % host)


def dpnorestart(conf):
    host = conf['host']
    logging.info('begining to deploy : %s' % conf['desc'])
    #kill process
    pid = execmd(_getpidcmd % host)


    logging.info('host : %s pid is %s will be killed.' % (host,pid))

    
    execmd(_killpidcmd % (host,pid))



    ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')

    srcpath = conf['remote']
    dstpath = srcpath + '_' + ts

    logging.info('backup files from %s to %s .' % (srcpath,dstpath))
    execmd(_bakcmd % (host,srcpath,dstpath))


    #print 'mkdir %s at %s' % (srcpath,host)

    #execmd(_mkpath % (host,srcpath))

    localpath = conf['local']
    logging.info('upload : ' + _uploadcmd % (localpath,host,'/data/www'))

    execmd(_uploadcmd % (localpath,host,'/data/www'))

    logging.info('startup tomcat.')

    execmd(_startcmd % host)

    logging.info('%s deploy over.' % host)




def deploy(conf):
    """
    deploy web file to the host in the conf
    """
    if conf['deploy']:
        if conf['restart']:
            dpwithrestart(conf)
        else:
            dpnorestart(conf)

    else:
        logging.info('%s will be not deploy' % conf['host'])


if __name__ == '__main__':
    for k in hostconf:
        deploy(hostconf[k])

